﻿#region using
using System;
using System.Collections.Generic;
using System.Windows;
using SLTimeZoneHelper;
using SLTimeZoneHelper.CRM2011;
using SilverCrmSoap.CrmSdk;
using TimeZoneTest.Model;

#endregion

namespace TimeZoneTest.Data_Layer
{
   public class CrmProxy
   {
      #region Fields
      private static volatile CrmProxy instance;
      private static readonly object SyncRoot = new Object();
      private IOrganizationService _crmService;
      #endregion Fields

      #region Properties and Events
      public static CrmProxy Instance
      {
         get
         {
            if (instance == null)
            {
               lock (SyncRoot)
               {
                  if (instance == null)
                  {
                     instance = new CrmProxy();
                  }
               }
            }

            return instance;
         }
      }

      public event EventHandler AsyncStarted;
      public event EventHandler AsyncStopped;
      #endregion Properties and Events

      #region ctors
      protected CrmProxy()
      {
         _crmService = SilverCrmSoap.Helpers.SoapHelper.SoapClient.ChannelFactory.CreateChannel();
      }
      #endregion ctors

      #region Methods      
      public void GetTimeZone(int timeZoneCode, Action<AsyncReponse<TimeZone>> postProcessor)
      {
         TimeZoneAdapter userAdapter = new TimeZoneAdapter(_crmService);
         userAdapter.GetTimeZoneCompleted += (sender, args) =>
            {
               postProcessor(new AsyncReponse<TimeZone>(args.TimeZone, args.Exception != null, args.Exception));
               RaiseAsyncStopped();
            };

         RaiseAsyncStarted();
         userAdapter.GetTimeZone(timeZoneCode);
      }

      public void GetAllTimeZones(Action<AsyncReponse<List<TimeZone>>> postProcessor)
      {
         TimeZoneAdapter userAdapter = new TimeZoneAdapter(_crmService);
         userAdapter.GetAllTimeZonesCompleted += (sender, args) =>
         {
            postProcessor(new AsyncReponse<List<TimeZone>>(args.TimeZones, args.Exception != null, args.Exception));
            RaiseAsyncStopped();
         };

         RaiseAsyncStarted();
         userAdapter.GetAllTimeZones();
      }

      private void RaiseAsyncStarted()
      {
         if (AsyncStarted != null)
         {
            Deployment.Current.Dispatcher.BeginInvoke(() => AsyncStarted(this, EventArgs.Empty));
         }
      }

      private void RaiseAsyncStopped()
      {
         if (AsyncStopped != null)
         {
            Deployment.Current.Dispatcher.BeginInvoke(() => AsyncStopped(this, EventArgs.Empty));
         }
      }
      #endregion Methods
   }
}